require('es6-promise').polyfill();
require('isomorphic-fetch');
// import fetch from "isomorphic-fetch";
// import {Promise} from "es6-promise";
import {setSignConfig, setVersion, suffix} from "./httputils";
import _ from "lodash/object";
import Cookie from 'cookies-js';

const env = `${process.env.NODE_ENV}`;

class Http {
    constructor() {
        this.instance = null;
        this.access_token = null;
    }

    //@yu 2016.12.14 加入扩展接口多端API
    setConfig(objConfig) {
        //先对【null，undefined，'', 0】等做一次判定  这些传入的都使用默认微信商城http配置
        let bLegalParam = false;
        if (!!objConfig && ((typeof objConfig) == "object" )) {
            if ((objConfig instanceof String) || (objConfig instanceof Date) ||
                (objConfig instanceof Array) || (objConfig instanceof Number) ||
                (objConfig instanceof Boolean) || (objConfig instanceof Function)) {
                bLegalParam = false;
            } else {
                bLegalParam = true;
            }
        }

        //设置签名公有参数
        if (bLegalParam && objConfig.channel) {
            setSignConfig(objConfig.channel);
        }

        //设置签名公有参数版本信息
        if (bLegalParam && objConfig.version) {
            setVersion(objConfig.version);
        }
    }


    setAccessToken(access_token) {
        this.access_token = access_token;
    }

    getSignedURL(options) {
        const {
            url,
            params,
            headers
        } = options;
        let newParmas = _.assign({}, params);
        if (this.access_token) {
            newParmas.access_token = this.access_token;
        }
        let signedObj = suffix(newParmas);
        if (this.access_token) {
            signedObj.access_token = this.access_token;
        }
        newParmas = _.assign(signedObj, params);
        const paramsString = _jsonToQueryString(newParmas, true);
        const api = `${url}${paramsString}`;
        return api;
    }

    post(options) {
        const {
            url,
            params,
            appCode
        } = options;

        if (!url) {
            console.log("url cannot be null");
            return;
        }
        // console.log("asdasdasda");
        // 去除无效的参数
        //这里有bug，参数为false 和参数为0  会被自动过滤掉,暂时去掉 by tao 17.11.06
        let filterPrams = {};
        for (let key in params) {
            // if (typeof params[key] === 'undefined' || params[key] === '') { continue; } // 过滤未定义和空串
            if (typeof params[key] === 'undefined') {
                continue;
            } // 过滤未定义 by v 17.12.1
            // if (params[key]) {
            filterPrams[key] = params[key];
            if (params[key] !== null && params[key]._isAMomentObject) {
                filterPrams[key] = params[key].unix() * 1000
            }
            // }
        }

        let newParmas = _.assign({}, filterPrams);
        if (this.access_token) {
            newParmas.access_token = this.access_token;
        }
        newParmas.json = JSON.stringify(filterPrams);
        let signedObj = suffix(newParmas);
        if (this.access_token) {
            signedObj.access_token = this.access_token;
        }
        const paramsStringWithQuestionMark = _jsonToQueryString(signedObj, true);
        const paramsStringWithoutQuestionMark = _jsonToQueryString(signedObj, false);
        let api = null;
        if (url.indexOf("?") != -1) {
            //url里面已经使用"?"拼接了参数，所以signedObj不能带"?",使用"&"拼接参数
            api = `${url}&${paramsStringWithoutQuestionMark}`;
        } else {
            api = `${url}${paramsStringWithQuestionMark}`;
        }

        let headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-YH-APP': appCode
        };
        if (env === "development") {
            headers["X-YH-UserId"] = 10001;
            headers["X-YH-UserDisplayName"] = "5pys5Zyw5byA5Y+R";
            headers["X-YH-UserLoginName"] = "bG9jYWwgZGV2ZWxvcA==";
            if (window.location.href.indexOf("liutao.com") >= 0) {
                headers["X-YH-RequestFeature"] = "liutao";
            } else if (window.location.href.indexOf("wangzhenfeng.com") >= 0) {
                headers["X-YH-RequestFeature"] = "wangzhenfeng";
            }
        }

        return fetch(api, {
            method: 'POST',
            //mode:'no-cors',
            headers: headers,
            credentials: 'same-origin',
            body: JSON.stringify(filterPrams),
        })
            .then((data) => {
                if (data.code === 41002) {
                    return window.location.href = '/signin';
                }
                return Promise.resolve(data);
            })
            .catch((error) => {
                return Promise.reject(error);
            });
    }

    upload(options) {
        const {
            url,
            file,
            group,
            md5,
            appCode
        } = options;

        if (!url || !file) {
            console.log("url/file cannot be null");
            return;
        }
        const formData = new FormData();
        formData.append('file', file);
        formData.append('filename', file.name);
        formData.append('ownserver', appCode);
        if (group) {
            formData.append('groupid', group);
        }
        if (md5) {
            formData.append('md5', md5);
        }
        let ticket = Cookie.get('uploadticket');
        if (env === "development") {
            ticket = "BLYQDV42h9RfqJc0luXVpbpNs70HNG3pivxtIn27qng=";
        }
        return fetch(url, {
            method: 'POST',
            body: formData,
            headers: {
                'ticket': ticket,
                'X-YH-APP': appCode
            },
        }).then(function(response) {
            return response.json();
        }).then((data) => {
            if (data.code == 41002) {
                return window.location.href = '/signin';
            }
            return Promise.resolve(data);
        }).catch((error) => {
            return Promise.reject(error);
        });
    }

    static getInstance() {
        if (!this.instance) {
            this.instance = new Http();
        }
        return this.instance;
    }
}

const Http = Http.getInstance();
export default Http;


function _jsonToQueryString(json, hasQuestionMark) {
    if (hasQuestionMark) {
        return '?' +
            Object.keys(json).map(function (key) {
                return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]);
            }).join('&');
    } else {
        return Object.keys(json).map(function (key) {
            return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]);
        }).join('&');
    }
}
